//
// Copyright 2023 The Sparrow Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef SPARROW_IMPL_FILE_H_
#define SPARROW_IMPL_FILE_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

#include "sparrow/impl/export.h"

#ifdef _WIN32
typedef void *sp_handle_t;
#else
typedef int sp_handle_t;
#endif

#define INVALID_FILE_HANDLE (sp_handle_t)(-1);

#define FS_READ_ONLY     1
#define FS_WRITE_ONLY    2
#define FS_READ_WRITE    4
#define FS_CREATE        8
#define FS_TRUNCATE      16
#define FS_OPEN_EXISTING 32

enum sp_where_t { FSW_BEGIN = 0, FSW_CURRENT, FSW_END };

sp_handle_t spf_open(const char *path, int option, int share);
int spf_close(sp_handle_t fd);

int spf_read_offset(sp_handle_t fd, void *buff, int size, int64_t offset);
int spf_read(sp_handle_t fd, void *buff, int size);

int spf_write_offset(sp_handle_t fd, const void *buff, int size, int64_t offset);
int spf_write(sp_handle_t fd, const void *buff, int size);

int64_t spf_offset(sp_handle_t fd);
int spf_set_offset(sp_handle_t fd, int64_t offset, enum sp_where_t where);

// allocate file space
int spf_reserve(sp_handle_t fd, int64_t offset, int64_t length);

// after calling this function
// the file pointer position maybe changed on unix systems
int64_t spf_size(sp_handle_t fd);

// truncate file
int spf_truncate(sp_handle_t fd, int64_t size);

#define IsValidFileHandle(fd) (fd != INVALID_FILE_HANDLE)

// ----------------------------------

int64_t sp_file_size(const char *p);
int sp_file_delete(const char *p);
int sp_file_rename(const char *oldpath, const char *newpath);
int sp_mk_dir(const char *dir);
int sp_rm_dir(const char *dir);

// If the file exists return 1, otherwise return 0
int sp_file_exists(const char *p);

#ifdef __cplusplus
} /* end extern "C" */
#endif

#endif // SPARROW_IMPL_FILE_H_
